const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const app = express();

app.use(session({
    name:'sid',//设置返回cookie的名字
    secret:'cty',//设置参与加密字符串
    saveUninitialized:false,//是否每次请求都设置一个cookie用来存储session的id
    resave:true,//是否在每次请求时重新保存session
    store:MongoStore.create({
        mongoUrl:'mongodb://127.0.0.1:27017/bilibili'//mongodb的连接
    }),
    cookie:{
        httpOnly:true,//开启后端后js无法操作
        maxAge:1000 * 60 * 5//这一条时控制sessionID的过期时间!!!!
    }
}));



app.get('/',(req, res) => {
    res.send('home');
});

//登录
app.get('/login',(req,res) => {
    if (req.query.username === 'admin' && req.query.password === 'admin') {
        req.session.username = 'admin';
        res.send('登录成功');
        return;
    }
    res.send('登录失败~~');
});


//读取session
app.get('/cart',(req, res) => {
    if (req.session.username) {
        res.send(`欢迎您 ${req.session.username}`);
        return;
    };
    res.send('您还没有登录~~~~');
});

app.get('/logout',(req, res) => {
    req.session.destroy(() => {
        res.send('退出成功');
    });
});



app.listen(3000);